﻿<template>
  <div class="etQuestionCate-container">
    <el-card shadow="hover" :body-style="{ paddingBottom: '0' }">
      <el-form :model="queryParams" ref="queryForm" :inline="true">
        <el-form-item label="所属题库" required>
          <el-select 
            v-model="selectedBankId" 
            placeholder="请选择题库"
            filterable
            clearable
            @change="handleBankChange"
          >
            <el-option 
              v-for="item in bankOptions" 
              :key="item.id" 
              :label="item.name" 
              :value="item.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="分类名称">
          <el-input v-model="queryParams.name" placeholder="分类名称" clearable @input="handleFilter" />
        </el-form-item>
        <el-form-item label="状态">
          <el-select v-model="queryParams.status" placeholder="状态" clearable @change="handleFilter">
            <el-option label="启用" :value="1" />
            <el-option label="禁用" :value="0" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button-group>
            <el-button type="primary" icon="ele-Search" @click="handleQuery"> 查询 </el-button>
            <el-button icon="ele-Refresh" @click="resetQuery"> 重置 </el-button>
            <el-button :icon="isExpand ? 'ele-FolderOpened' : 'ele-Folder'" @click="toggleExpand">
              {{ isExpand ? '收起' : '展开' }}
            </el-button>
          </el-button-group>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="ele-Plus" @click="openAddEtQuestionCate"> 新增 </el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <el-card class="full-table" shadow="hover" style="margin-top: 5px">
      <el-table
        ref="tableRef"
        :data="filteredTableData"
        v-loading="loading"
        row-key="id"
        :tree-props="{ children: 'children', hasChildren: 'hasChildren' }"
        :default-expand-all="isExpand"
        border>
        <el-table-column label="分类名称" min-width="200" show-overflow-tooltip>
          <template #default="scope">
            <span>{{ scope.row.name }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="description" label="描述" min-width="150" show-overflow-tooltip />
        <el-table-column label="状态" width="90" align="center" show-overflow-tooltip>
          <template #default="scope">
            <el-tag type="success" v-if="scope.row.status === 1">启用</el-tag>
            <el-tag type="danger" v-else>禁用</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="orderNo" label="排序" width="90" align="center" show-overflow-tooltip />
        <el-table-column label="修改记录" width="100" align="center" show-overflow-tooltip>
          <template #default="scope">
            <ModifyRecord :data="scope.row" />
          </template>
        </el-table-column>
        <el-table-column label="操作" width="240" fixed="right" align="center" show-overflow-tooltip>
          <template #default="scope">
            <el-button icon="ele-Plus" size="small" text type="primary" @click="openAddChildCate(scope.row)">
              新增子分类
            </el-button>
            <el-button icon="ele-Edit" size="small" text type="primary" @click="openEditEtQuestionCate(scope.row)">
              编辑
            </el-button>
            <el-button icon="ele-Delete" size="small" text type="danger" @click="delEtQuestionCate(scope.row)">
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>

    <EditDialog ref="editDialogRef" :title="editTitle" @handleQuery="handleQuery" />
  </div>
</template>

<script lang="ts" setup name="etQuestionCate">
import { ref, computed, onMounted } from 'vue';
import { ElMessageBox, ElMessage } from 'element-plus';
import EditDialog from './component/editDialog.vue';
import ModifyRecord from '/@/components/table/modifyRecord.vue';
import { getEtQuestionCateTree, deleteEtQuestionCate } from '/@/api/main/et-question-cate';
import { pageEtQuestionBank } from '/@/api/main/et-question-bank';

interface TableData {
  id: number;
  name: string;
  status: number;
  children?: TableData[];
  [key: string]: any;
}

const editDialogRef = ref();
const tableRef = ref();
const loading = ref(false);
const tableData = ref<TableData[]>([]);
const editTitle = ref('');
const isExpand = ref(false);
const selectedBankId = ref<number>();
const bankOptions = ref<any[]>([]);

const queryParams = ref({
  name: undefined as string | undefined,
  status: undefined as number | undefined,
});

// 过滤后的表格数据
const filteredTableData = computed(() => {
  if (!queryParams.value.name && queryParams.value.status === undefined) {
    return tableData.value;
  }

  const filterNode = (data: TableData): TableData | null => {
    const nameMatch = !queryParams.value.name || 
      data.name.toLowerCase().includes((queryParams.value.name || '').toLowerCase());
    const statusMatch = queryParams.value.status === undefined || 
      data.status === queryParams.value.status;

    if (nameMatch && statusMatch) return data;

    if (data.children && data.children.length) {
      const children = data.children
        .map(child => filterNode(child))
        .filter((child): child is TableData => child !== null);
      
      if (children.length) {
        return { ...data, children };
      }
    }
    return null;
  };

  return tableData.value
    .map(node => filterNode(node))
    .filter((node): node is TableData => node !== null);
});


// 获取题库列表
const getBankOptions = async () => {
  try {
    const res = await pageEtQuestionBank({ page: 1, pageSize: 100 });
    bankOptions.value = res.data.result?.items || [];
  } catch (error) {
    console.error('获取题库列表失败:', error);
  }
};

// 题库选择改变
const handleBankChange = async (value: number) => {
  if (!value) {
    tableData.value = [];
    return;
  }
  await handleQuery();
};

// 查询操作
const handleQuery = async () => {
  if (!selectedBankId.value) {
    ElMessage.warning('请先选择题库');
    return;
  }
  
  loading.value = true;
  try {
    const res = await getEtQuestionCateTree(selectedBankId.value);
    tableData.value = res.data.result ?? [];
    isExpand.value = true;
  } finally {
    loading.value = false;
  }
};

// 重置操作
const resetQuery = () => {
  queryParams.value = {
    name: undefined,
    status: undefined,
  };
  handleQuery();
};

// 打开新增页面
const openAddEtQuestionCate = () => {
  if (!selectedBankId.value) {
    ElMessage.warning('请先选择题库');
    return;
  }
  editTitle.value = '添加分类';
  editDialogRef.value?.openDialog({ 
    status: 1, 
    orderNo: 100,
    questionBankId: selectedBankId.value 
  });
};

// 打开编辑页面
const openEditEtQuestionCate = (row: any) => {
  editTitle.value = '编辑分类';
  editDialogRef.value?.openDialog(row);
};

// 删除
const delEtQuestionCate = (row: any) => {
  const message = row.children?.length 
    ? `确定删除分类：【${row.name}】?\n该分类下有 ${row.children.length} 个子分类，删除后将同时删除所有子分类！`
    : `确定删除分类：【${row.name}】?`;

  ElMessageBox.confirm(message, '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning',
    customClass: 'custom-message-box'
  })
    .then(async () => {
      await deleteEtQuestionCate({ id: row.id });
      handleQuery();
      ElMessage.success('删除成功');
    })
    .catch((action) => {
      if (action === 'cancel') {
        ElMessage.info('已取消删除');
      }
    });
};

// 展开/收起所有节点
const toggleExpand = () => {
  isExpand.value = !isExpand.value;
  const data = filteredTableData.value;
  
  const toggleRows = (rows: TableData[]) => {
    rows.forEach(row => {
      tableRef.value?.toggleRowExpansion(row, isExpand.value);
      if (row.children && row.children.length > 0) {
        toggleRows(row.children);
      }
    });
  };
  
  toggleRows(data);
};

// 本地过滤处理
const handleFilter = () => {
  // 过滤后自动展开所有节点以显示匹配结果
  if (queryParams.value.name || queryParams.value.status !== undefined) {
    isExpand.value = true;
    // 等待DOM更新后展开
    setTimeout(() => {
      const data = filteredTableData.value;
      const expandRows = (rows: any[]) => {
        rows.forEach(row => {
          tableRef.value?.toggleRowExpansion(row, true);
          if (row.children && row.children.length > 0) {
            expandRows(row.children);
          }
        });
      };
      expandRows(data);
    }, 100);
  }
};

// 打开新增子分类页面
const openAddChildCate = (row: any) => {
  if (!selectedBankId.value) {
    ElMessage.warning('请先选择题库');
    return;
  }
  editTitle.value = '新增子分类';
  editDialogRef.value?.openDialog({ 
    status: 1, 
    orderNo: 100,
    parentId: row.id,
    questionBankId: selectedBankId.value 
  });
};

onMounted(() => {
  getBankOptions();
});
</script>

<style lang="scss" scoped>
.etQuestionCate-container {
  :deep(.el-card__body) {
    padding: 15px;
  }
  :deep(.el-select) {
    width: 100%;
  }
}

:deep(.custom-message-box) {
  .el-message-box__message {
    p {
      margin-bottom: 10px;
    }
    .el-checkbox {
      margin-left: 0;
    }
  }
}
</style>

